package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.JsonUtils;
import com.heima.file.service.MinioService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {

    @Autowired
    private Configuration configuration;
    @Autowired
    private MinioService minioService;
    @Autowired
    private ApArticleService apArticleService;

    @Override
    //@Async //当前方法是异步执行方法
    public void buildArticleToMinIO(ApArticle apArticle, String content) {
//        获取文章id
        Long articleId = apArticle.getId();
        if(StringUtils.isBlank(content)){
            log.error("content内容为空，直接返回articleId={}",articleId);
            return ;
        }
        try{
//        1、生成静态页
            Template template = configuration.getTemplate("article.ftl");
            log.info("获取到template");
            Map<String,Object>  dataMap = new HashMap<>();
//        把content的json字符串转java对象
            List<Map<String,Object>> list = JsonUtils.nativeRead(content, new TypeReference<List<Map<String,Object>>>() {});
            dataMap.put("content", list);
//      使用api生成静态页
            StringWriter out = new StringWriter();
            template.process(dataMap,out);
//        2、上传到minio
//        把StringWriter转inputStream
            ByteArrayInputStream inputStream = new ByteArrayInputStream(out.toString().getBytes());
            String htmlName = articleId + ".html";
//        上传miniio 获取html文件的路径
            String htmlPath = minioService.uploadHtmlFile("", htmlName, inputStream);

//        3、保存文章路径
//        update ap_article set static_url =? where id=?
            UpdateWrapper<ApArticle> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda().
                    eq(ApArticle::getId,articleId).
                    set(ApArticle::getStaticUrl,htmlPath);
            apArticleService.update(updateWrapper);
        }catch(Exception e){
            log.error("生成静态页面异常！");
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }

    }
}
